package cn.cdg.mall.service.impl;

import cn.cdg.mall.mapper.TicketMapper;
import cn.cdg.mall.mapper.UpMapper;
import cn.cdg.mall.pojo.po.PersonPO;
import cn.cdg.mall.pojo.po.TicketPO;
import cn.cdg.mall.pojo.po.UpPO;
import cn.cdg.mall.pojo.po.UserPO;
import cn.cdg.mall.service.TicketService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TicketServiceImpl implements TicketService {
    @Autowired
    private TicketMapper ticketMapper;

    @Autowired
    private UpMapper upMapper;

    @Override
    public List<TicketPO> selectAllTickets(UserPO userPO) {
        QueryWrapper<UpPO> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_no", userPO.getUserNo());
        List<UpPO> ups = upMapper.selectList(queryWrapper1);
        List<String> ids = ups.stream().map(UpPO::getID).collect(Collectors.toList());
        List<TicketPO> ticketPOs = new ArrayList<>();
        for (String id : ids) {
            QueryWrapper<TicketPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            List<TicketPO> tmp = ticketMapper.selectList(queryWrapper);
            ticketPOs.addAll(tmp);
        }
        return ticketPOs.isEmpty() ? null : ticketPOs;
    }

    @Override
    public List<TicketPO> selectByCreateDate(String createDate) {
        QueryWrapper<TicketPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_date", createDate);
        List<TicketPO> ticketPOs = ticketMapper.selectList(queryWrapper);
        return ticketPOs.isEmpty() ? null : ticketPOs;
    }

    @Override
    public TicketPO selectOneByTicketNo(long TicketNo) {
        QueryWrapper<TicketPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ticket_no", TicketNo);
        List<TicketPO> ticketPOs = ticketMapper.selectList(queryWrapper);
        return ticketPOs.isEmpty() ? null : ticketPOs.get(0);
    }

    @Override
    public boolean addTicket(TicketPO ticket) {
        TicketPO result = selectOneByTicketNo(ticket.getTicketNo());
        if (result == null) {
            ticketMapper.insert(ticket);
            return true;
        }
        return false;
    }


}
